/**
 *
 *@author ZhouLan
 *@version 1.0.0
 */

import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import hilog from '@ohos.hilog';
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
import { Communications, SessionMessage } from '../entity/Communications';
import { ApplicationConfig } from '../entity/ApplicationConfig';
import { configs } from '../configs/Config';
import { Request } from '../util/Requests';


export default class EntryAbility extends UIAbility {
  storage:LocalStorage
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    globalThis.context = this.context
    AppStorage.SetOrCreate<Communications>('communications',new Communications())
    AppStorage.SetOrCreate<number>('total',0)
    AppStorage.SetOrCreate<string[]>('currentOpposite',[''])
    AppStorage.SetOrCreate<string[]>('account',[])
    //如果接收到新的订单，或者某个时机需要刷新数据，可以更改此变量，并监视它的变化调用对应的函数
    AppStorage.SetOrCreate<number>('listener_order',0)
    AppStorage.SetOrCreate<number>('listener_goods',0)
    let applicationConfig:ApplicationConfig
    let httpUrl = configs.protocol.http+configs.domain+configs.port
    let wsUrl = configs.protocol.ws+configs.domain+configs.port
    globalThis.wsBaseUrl = wsUrl
    applicationConfig = new ApplicationConfig(wsUrl,httpUrl)
    globalThis.applicationConfig = applicationConfig
    globalThis.request = new Request(httpUrl);
    console.log(`routerMap长度:${(globalThis.request as Request).getRoutersMap.length}`)
    this.storage = new LocalStorage({'currentMessage':[] as SessionMessage[]})
  }

  onDestroy(): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index',this.storage, (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground(): void {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
